//引入axios请求
import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import sysCofig from '../config/index.js'
import tool from './root'
import { useRouter } from 'vue-router'

const router = useRouter()
// store
// import useUserStore from '@/store/modules/userStore.js'
// const store = useUserStore()
const BASE_API = import.meta.env.VITE_APP_API_URL
// 创建axios实例
const service = axios.create({
  baseURL: "/api", //所有的后端接口请求地址前缀部分(没有后端请求不用写)
  timeout: sysCofig.TIMEOUT, // 请求超时时间,这里15秒
})
const reloadCodes = [401, 1011007, 1011008]

// request拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem(sysCofig.TOKEN_NAME);
  if (token && !config.headers[sysCofig.TOKEN_NAME]) {
    config.headers[sysCofig.TOKEN_NAME] = token
  }
  return config
}, error => {
  console.log("sss",error)
  ElMessage.error("服务器加载中，请稍后")
  return Promise.reject(error)
})
const error = () => {
    // loginBack.value = true
    tool.data.remove(sysCofig.TOKEN_NAME)
    ElMessage.error("登录已失效， 请重新登录")
    window.location.reload()
  }
// response拦截器
service.interceptors.response.use(
  response => {
    //对数据返回做什么
    const res = response.data
    console.log("返回参数", res)
    const config = response.config
    // custom 表示自定义
    if (res.code !== 200) {
      //   if (res.status_code === 1002) {
      //     loginOut()
      //   } else if (loginVerify(res, config)) { // 登录功能验证
      //     return res
      //   } else {
      // Message({
      //   message: res.status || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      //   }
      console.log("reloadCodes.includes(res.code)",reloadCodes.includes(res.code));
      if(reloadCodes.includes(res.code)){
        error()
      }else{
        ElMessage.error(res.msg)
      }
      return Promise.reject(res)
    } else{
      if (response.headers['authorization'] || response.headers['Authorization']) {
        const _token = response.headers['authorization'] || response.headers['Authorization']
        // store.dispatch('user/setToken', _token.split('Bearer ')[1])
      }
      return Promise.resolve(res)
    }
  },
  error => {
    console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

// 适配器, 用于适配不同的请求方式
export const baseRequest = (url, value = {}, method = 'post', options = {}) => {
  console.log("BASE_API", BASE_API)
  url = BASE_API + url
  if (method === 'post') {
    return service.post(url, value, options)
  }
  else if (method === 'get') {
    return service.get(url, {
      params: value,
      ...options,
      paramsSerializer: (params) => {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    })
  }
  else if (method === 'formdata') {
    // form-data表单提交的方式
    return service.post(url, qs.stringify(value), {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...options
    })
  }
  else if (method === 'download') {
    const key = 'updatable'
    message.loading({ content: '下载中...', key })
    // 下载文件的方式
    return service
      .get(url, {
        params: value,
        responseType: 'blob',
        ...options
      })
      .then((res) => {
        //   downloadBlob(res)
        message.success({ content: '下载成功!', key, duration: 2 })
        Promise.resolve(res.data)
      })
      .catch((error) => {
        message.error({ content: '下载失败!', key, duration: 2 })
        Promise.reject(error.toString())
      })
  }
  else if (method === 'postDownload') {
    const key = 'updatable'
    message.loading({ content: '下载中...', key })
    return service.post(url, value, { ...options, responseType: 'blob' }).then((res) => {
      // downloadBlob(res)
      message.success({ content: '下载成功!', key, duration: 2 })
      Promise.resolve(res.data)
    })
      .catch((error) => {
        message.error({ content: '下载失败!', key, duration: 2 })
        Promise.reject(error.toString())
      })
  }
  else if (method === 'websocket') {
    // websocket的方式
    return service.get(url, {
      params: value,
      ...options
    })
  }
  else {
    // 其他请求方式，例如：put、delete
    return service({
      method,
      url,
      data: value,
      ...options
    })
  }
}
export const moduleRequest
  = moduleUrl =>
    (url, ...arg) => {
      return baseRequest(moduleUrl + url, ...arg)
    }
export default service